import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import win32com.client
import os
from pathlib import Path
import sv_ttk
from tkinter.font import Font
import time  # 添加 time 模块用于等待文件操作完成


class WPSExcelToPDFConverter:
    def __init__(self, root):
        self.root = root
        self.root.title("Excel表格批量转PDF (WPS版)")
        self.root.geometry("800x600")
        # 应用现代深色主题
        sv_ttk.set_theme("dark")

        # 配置默认设置
        self.config = {
            'page_orientation': 'landscape',
            'fit_to_page': True,
            'scale': 100,
            'center_horizontal': True,
            'center_vertical': True
        }

        self.setup_ui()

    def setup_ui(self):
        container = ttk.Frame(self.root)
        container.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)

        # 设置标题
        title_font = Font(family="Helvetica", size=24, weight="bold")
        title = ttk.Label(container, text="Excel表格批量转PDF (WPS版)", font=title_font)
        title.pack(pady=(0, 20))

        # 左侧面板 - 文件列表
        left_panel = ttk.Frame(container)
        left_panel.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

        files_frame = ttk.LabelFrame(left_panel, text="文件列表", padding=10)
        files_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10))

        # 文件列表框和滚动条
        self.files_listbox = tk.Listbox(
            files_frame,
            selectmode=tk.MULTIPLE,
            font=("Helvetica", 10),
            background="#2d2d2d",
            foreground="white",
            selectbackground="#007acc"
        )
        scrollbar = ttk.Scrollbar(files_frame, orient=tk.VERTICAL)
        self.files_listbox.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.files_listbox.yview)

        self.files_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

        # 右侧面板 - 设置和控制
        right_panel = ttk.Frame(container)
        right_panel.pack(side=tk.RIGHT, fill=tk.BOTH, padx=(20, 0))

        # 设置区域
        settings_frame = ttk.LabelFrame(right_panel, text="导出设置", padding=10)
        settings_frame.pack(fill=tk.X, pady=(0, 10))

        # 页面方向设置
        ttk.Label(settings_frame, text="页面方向:").pack(anchor=tk.W)
        self.orientation_var = tk.StringVar(value="landscape")
        ttk.Radiobutton(settings_frame, text="横向", value="landscape",
                        variable=self.orientation_var).pack(anchor=tk.W)
        ttk.Radiobutton(settings_frame, text="纵向", value="portrait",
                        variable=self.orientation_var).pack(anchor=tk.W)

        # 页面居中设置
        ttk.Label(settings_frame, text="页面居中:", font=("Helvetica", 9, "bold")).pack(
            anchor=tk.W, pady=(10, 5))
        self.center_h_var = tk.BooleanVar(value=True)
        self.center_v_var = tk.BooleanVar(value=True)
        ttk.Checkbutton(settings_frame, text="水平居中",
                        variable=self.center_h_var).pack(anchor=tk.W)
        ttk.Checkbutton(settings_frame, text="垂直居中",
                        variable=self.center_v_var).pack(anchor=tk.W)

        # 缩放设置
        ttk.Label(settings_frame, text="缩放选项:",
                  font=("Helvetica", 9, "bold")).pack(anchor=tk.W, pady=(10, 5))
        self.fit_page_var = tk.BooleanVar(value=True)
        ttk.Checkbutton(settings_frame, text="适应页面宽度",
                        variable=self.fit_page_var).pack(anchor=tk.W)

        # 缩放比例设置
        scale_frame = ttk.Frame(settings_frame)
        scale_frame.pack(fill=tk.X, pady=5)
        self.scale_var = tk.IntVar(value=100)
        ttk.Label(scale_frame, text="缩放比例:").pack(side=tk.LEFT)
        scale_spin = ttk.Spinbox(scale_frame, from_=50, to=150,
                                 width=5, textvariable=self.scale_var)
        scale_spin.pack(side=tk.LEFT, padx=5)
        ttk.Label(scale_frame, text="%").pack(side=tk.LEFT)

        # 控制按钮
        button_frame = ttk.Frame(right_panel)
        button_frame.pack(fill=tk.X, pady=10)

        select_btn = ttk.Button(button_frame, text="选择文件",
                                command=self.select_files, style="Accent.TButton")
        select_btn.pack(fill=tk.X, pady=5)

        convert_btn = ttk.Button(button_frame, text="开始转换",
                                 command=self.convert_files, style="Accent.TButton")
        convert_btn.pack(fill=tk.X, pady=5)

        # 进度条和状态标签
        self.progress = ttk.Progressbar(right_panel, orient="horizontal", mode="determinate")
        self.progress.pack(fill=tk.X, pady=10)

        self.status_label = ttk.Label(right_panel, text="就绪", font=("Helvetica", 9))
        self.status_label.pack()

    def select_files(self):
        """选择要转换的Excel文件"""
        files = filedialog.askopenfilenames(
            title="选择Excel文件",
            filetypes=[("Excel files", "*.xlsx *.xls")]
        )
        self.files_listbox.delete(0, tk.END)
        for file in files:
            self.files_listbox.insert(tk.END, file)

    def convert_files(self):
        """批量转换Excel文件到PDF"""
        if self.files_listbox.size() == 0:
            messagebox.showwarning("警告", "请先选择Excel文件")
            return

        try:
            # 创建WPS应用程序实例
            excel = win32com.client.Dispatch("KET.Application")
            # 设置WPS为不可见
            excel.Visible = False
            # 禁用警告弹窗
            excel.DisplayAlerts = False

            total_files = self.files_listbox.size()
            self.progress["maximum"] = total_files

            for i in range(total_files):
                file_path = self.files_listbox.get(i)
                self.status_label["text"] = f"正在转换: {Path(file_path).name}"

                try:
                    # 打开工作簿
                    wb = excel.Workbooks.Open(file_path)

                    # 处理每个工作表
                    for ws in wb.Worksheets:
                        # WPS的页面设置
                        # 注意：WPS的页面方向设置与Microsoft Excel略有不同
                        ws.PageSetup.Orientation = 2 if self.orientation_var.get() == "landscape" else 1

                        # 设置页面居中
                        ws.PageSetup.CenterHorizontally = self.center_h_var.get()
                        ws.PageSetup.CenterVertically = self.center_v_var.get()

                        # 设置缩放
                        if self.fit_page_var.get():
                            ws.PageSetup.FitToPagesWide = 1
                            ws.PageSetup.FitToPagesTall = False
                        else:
                            ws.PageSetup.Zoom = self.scale_var.get()

                        # 自动调整列宽
                        ws.Columns.AutoFit()

                    # 生成PDF文件路径
                    pdf_path = str(Path(file_path).with_suffix('.pdf'))

                    # WPS的PDF导出
                    # 注意：WPS使用不同的PDF导出方法和参数
                    wb.ExportAsFixedFormat(0, pdf_path)

                    # 关闭工作簿前等待一小段时间确保导出完成
                    time.sleep(0.5)
                    wb.Close(SaveChanges=False)

                    # 再次等待以确保文件完全关闭
                    time.sleep(0.5)

                except Exception as e:
                    messagebox.showerror("错误", f"转换文件 {file_path} 时出错:\n{str(e)}")

                self.progress["value"] = i + 1
                self.root.update()

            # 关闭WPS应用程序
            excel.Quit()
            self.status_label["text"] = "转换完成!"
            messagebox.showinfo("完成", "所有文件已转换完成!")
            self.progress["value"] = 0

        except Exception as e:
            messagebox.showerror("错误", f"初始化WPS时出错:\n{str(e)}")
            self.status_label["text"] = "转换失败"
            self.progress["value"] = 0


if __name__ == "__main__":
    root = tk.Tk()
    app = WPSExcelToPDFConverter(root)
    root.mainloop()